package com.mlethe.library.multi.api;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.mlethe.library.multi.api.entity.ImageObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.UUID;

/**
 * 工具类
 */
final class Util {
    /**
     * Bitmap 格式化
     *
     * @param bitmap
     */
    static Bitmap bitmapFormat(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        int bitmapHeight = bitmap.getHeight();
        int bitmapWidth = bitmap.getWidth();
        int width = 300;
        if (width >= bitmapWidth) {
            return bitmap;
        }
        int height = (int) (bitmapHeight / (float) bitmapWidth * width);
        return bitmapFormat(bitmap, width, height);
    }

    /**
     * Bitmap 格式化
     *
     * @param bitmap
     * @param width  宽度
     * @param height 高度
     */
    static Bitmap bitmapFormat(Bitmap bitmap, int width, int height) {
        if (bitmap == null) {
            return null;
        }
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, width, height, true);
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }
        return thumbBmp;
    }

    /**
     * 将 Bitmap 转换为 byte[]
     *
     * @param bitmap
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            // 将 Bitmap 压缩到输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
            // 转换为 byte[]
            byte[] bytes = outputStream.toByteArray();
            outputStream.close();
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * url 转Bitmap
     *
     * @param url
     */
    static Bitmap url2bitmap(URL url) {
        Bitmap bitmap = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 状态随机值
     */
    @NonNull
    static String buildState() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取url
     *
     * @param urlString
     */
    static URL getUrl(String urlString) {
        try {
            return new URL(urlString);
        } catch (Throwable e) {
            return null;
        }
    }


    /**
     * 获取文件Uri
     *
     * @param context
     * @param path
     * @return
     */
    static Uri getUri(Context context, String path, @NonNull String authority) {
        return getUri(context, null, path, authority);
    }

    /**
     * 获取文件Uri
     *
     * @param context
     * @param path
     * @return
     */
    static Uri getUri(Context context, String pkgName, String path, @NonNull String authority) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Uri uri = FileProvider.getUriForFile(context, authority, file);
                if (!TextUtils.isEmpty(pkgName)) {
                    context.grantUriPermission(pkgName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                return uri;
            } catch (Exception e) {
                return null;
            }
        }
        return Uri.fromFile(file);
    }

    /**
     * 获取文件Uri
     *
     * @param context
     * @param file
     * @return
     */
    static Uri getUri(Context context, File file, @NonNull String authority) {
        return getUri(context, null, file, authority);
    }

    /**
     * 获取文件Uri
     *
     * @param context
     * @param file
     * @return
     */
    static Uri getUri(Context context, String pkgName, File file, @NonNull String authority) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Uri uri = FileProvider.getUriForFile(context, authority, file);
                if (!TextUtils.isEmpty(pkgName)) {
                    context.grantUriPermission(pkgName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                return uri;
            } catch (Exception e) {
                return null;
            }
        }
        return Uri.fromFile(file);
    }

    /**
     * 获取图片文件路径
     *
     * @param context
     * @param image
     * @param isLocal 是否只返回本地文件路径
     * @return
     */
    static String getFilePath(Context context, ImageObject image, boolean isLocal) {
        if (image == null) {
            return null;
        }
        String imagePath = image.getImagePath();
        Bitmap bitmap = image.getBitmap();
        byte[] imageData = image.getImageData();
        int drawableId = image.getDrawableId();
        try {
            if (bitmap != null && !bitmap.isRecycled()) {
                imagePath = bitmapToFile(context, bitmap);
            } else if (imageData != null && imageData.length > 0) {
                Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                imagePath = bitmapToFile(context, bmp);
                if (bmp != null && !bmp.isRecycled()) {
                    bmp.recycle();
                }
            } else if (drawableId != 0) {
                Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), drawableId);
                imagePath = bitmapToFile(context, bmp);
                if (bmp != null && !bmp.isRecycled()) {
                    bmp.recycle();
                }
            } else if (!TextUtils.isEmpty(imagePath)) {
                if (isLocal) {
                    URL url = Util.getUrl(imagePath);
                    if (url != null) {
                        // 网络图片
                        Bitmap bmp = Util.url2bitmap(url);
                        if (bmp != null) {
                            imagePath = bitmapToFile(context, bmp);
                            if (!bmp.isRecycled()) {
                                bmp.recycle();
                            }
                        }
                    }
                }
                return imagePath;
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        if (TextUtils.isEmpty(imagePath)) {
            imagePath = image.getImagePath();
        }
        return imagePath;
    }

    /**
     * bitmap 转为 文件
     *
     * @param context
     * @param bitmap
     * @return 文件路径
     */
    static String bitmapToFile(Context context, Bitmap bitmap) {
        if (context == null || bitmap == null || bitmap.isRecycled()) {
            return null;
        }
        String cacheDir = getCacheDir(context);
        File pathFile = new File(cacheDir);
        FileOutputStream outputStream = null;
        try {
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String fileName = System.currentTimeMillis() + "_" + String.format("%04d", new Random().nextInt(10000)) + ".png";
            File file = new File(pathFile, fileName);
            outputStream = new FileOutputStream(file);
            boolean success = bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.flush();
            if (success) {
                return file.getPath();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取APP缓存目录
     * Android 29 弃用 Environment.getExternalStorageDirectory() 方法
     *
     * @param context 上下文
     * @return path = /storage/emulated/0/Android/data/包名/cache/multi/share/
     */
    static String getCacheDir(Context context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                return context.getExternalCacheDir().getAbsolutePath() + "/multi/share/";
            }
        } catch (Exception e) {
        }
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/Android/data/" + context.getPackageName() + "/cache/multi/share/";
    }
}
